package com.springboot.mybatis.service.threaddemo;

/**
 * @author sunyt31481
 * @date 2020/8/10 14:48
 * @description 使用synchronized锁，进行线程间的交替运行，此锁有一特点，即当代码运行结束后，才会释放锁
 */
public class SynchronizedDemo {
    public static void main(String[] args) {
        Factory factory = new Factory();
        //假设创建12个线程，加锁的目的即是限制一次只能有一个线程调用方法 factory.creatProduct(i)
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for (int i=0;i<12;i++){
                    factory.creatProduct(i);
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for (int i=0;i<12;i++){
                    factory.sellProduct(i);
                }
            }
        }).start();

    }


}


class Factory{
    private boolean isCreate = true;
    public synchronized void creatProduct(int i){
        while (!isCreate){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for (int j=0;j<=100;j++){
            System.out.println("第"+i+"轮生产,产出"+j+"件产品");
        }
        isCreate = false;
        this.notify();
    }

    public synchronized void sellProduct(int i){
        while (isCreate){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for (int j=0;j<=20;j++){
            System.out.println("第"+i+"轮消费，消费"+j+"件产品");
        }
        isCreate = true;
        this.notify();
    }
}
